package com.bilibili.juc.cf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ComprehensiveCompletableFutureExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(4);

        // 4.2. 创建和启动异步计算
        CompletableFuture<Boolean> inventoryCheckFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("检查库存...");
            return true; // 假设库存充足
        }, executor);

        // 4.4. 正常完成时的转换
        CompletableFuture<String> orderCreationFuture = inventoryCheckFuture.thenApplyAsync(
                ordered -> "ORDER-" + ordered,
                executor
        );

        // 4.5. 组合 CompletableFuture
        CompletableFuture<String> paymentProcessingFuture = orderCreationFuture.thenComposeAsync(
                order -> CompletableFuture.supplyAsync(() -> {
                    System.out.println("处理支付...");
                    return "PAYMENT-" + order;
                }),
                executor
        );

        // 4.6. 异常处理
        CompletableFuture<String> exceptionHandledFuture = paymentProcessingFuture.exceptionally(
                ex -> "EXCEPTION-" + ex.getMessage()
        );

        // 4.7. 完成时的回调（无论成功或失败）
        CompletableFuture<String> finalResultFuture = exceptionHandledFuture.handle((result, ex) -> {
            if (ex == null) {
                System.out.println("订单处理成功: " + result);
                return result;
            } else {
                System.out.println("订单处理失败: " + ex.getMessage());
                return "FAILURE-" + ex.getMessage();
            }
        });

        // 4.8. 等待其他 CompletableFuture
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                inventoryCheckFuture,
                orderCreationFuture,
                paymentProcessingFuture,
                exceptionHandledFuture,
                finalResultFuture
        );

        // 4.9. 任意一个或全部完成
        CompletableFuture<Object> anyOfFutures = CompletableFuture.anyOf(
                inventoryCheckFuture,
                orderCreationFuture,
                paymentProcessingFuture,
                exceptionHandledFuture,
                finalResultFuture
        );

        // 4.10. 超时和取消
        CompletableFuture<String> timeoutFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "TIMEOUT";
        }).orTimeout(1, TimeUnit.SECONDS);

        // 4.11. 结果获取
        finalResultFuture.thenAccept(result -> {
            System.out.println("最终结果: " + result);
        });

        timeoutFuture.exceptionally(ex -> {
            System.out.println("超时异常: " + ex.getMessage());
            return null;
        });

        // 等待所有任务完成
        allFutures.join();

        // 关闭线程池
        executor.shutdown();
    }
}
